﻿using System;
using System.Collections.Generic;
using DDDProjectSample.Domain;
using DDDProjectSample.Domain.Repositories;
using Castle.Facilities.NHibernateIntegration;
using NHibernate;
using NHibernate.Expression;

namespace DDDProjectSample.Infrastructure.Repositories
{
    public class TopicRepository : BaseRepository<Topic>, ITopicRepository
    {
        /// <summary>
        /// Creates a new instance of class TopicRepository
        /// </summary>
        /// <param name="sessionManager">The Nhibernate Session Manager</param>
        public TopicRepository(
            ISessionManager sessionManager) : base(sessionManager)
        {
        }

        #region ITopicRepository Members

        public ICollection<Topic> FindByForumId(long forumId)
        {
            using (ISession session = SessionManager.OpenSession())
            {
                return session.CreateCriteria(typeof(Topic))
                            .SetFetchMode("Author", FetchMode.Join)
                            .Add(Expression.Eq("Forum.Id", forumId))
                            .AddOrder(Order.Asc("CreationDate"))
                            .List<Topic>();
            }
        }

        public int CountByUserId(long userId, DateTime date1, DateTime date2)
        {
            using (ISession session = SessionManager.OpenSession())
            {
                return session.CreateCriteria(typeof(Topic))
                            .Add(Expression.Eq("Author.Id", userId))
                            .Add(Expression.Between("CreationDate", date1, date2))
                            .SetProjection(Projections.Count("Id"))
                            .UniqueResult<int>();
            }
        }

        #endregion
    }
}
